﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Fizzler.Systems.HtmlAgilityPack;
using HtmlAgilityPack;

namespace WqHtmlAnchorSpider
{
    public class HtmlAnchorParser
    {
        public HtmlAnchorParser()
        {
        }

        public List<AnchorObj> GetAnchorObjs(string anchorType, string url, List<String> subStrs)
        {
            List<AnchorObj> anchors = new List<AnchorObj>();
            var html = new HtmlDocument();
            var web = new HtmlWeb();
            html = web.LoadFromBrowser(url);
            var document = html.DocumentNode;
            List<HtmlNode> nodes = new List<HtmlNode>(document.QuerySelectorAll("tr td a.subject"));
            if (nodes != null)
            {
                foreach (var node in nodes)
                {
                    if (node.InnerText.Contains("P】"))
                    {
                        if (subStrs == null || subStrs.Count == 0)
                        {
                            anchors.Add(new AnchorObj()
                            {
                                Type = anchorType,
                                Href = "http://duoguo.net/2048/" + node.GetAttributeValue("href", String.Empty),
                                Name = node.InnerText
                            });
                        }
                        else
                        {
                            foreach (var subStr in subStrs)
                            {
                                if (node.InnerText.Contains(subStr))
                                {
                                    anchors.Add(new AnchorObj()
                                    {
                                        Type = anchorType,
                                        Href = "http://duoguo.net/2048/" + node.GetAttributeValue("href", String.Empty),
                                        Name = node.InnerText
                                    });
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            return anchors;
        }

        public List<AnchorObj> GetAnchorObjs(string anchorType, string url)
        {
            return GetAnchorObjs(anchorType, url, null);
        }
    }
}